package com.wz.dhs.utils;

import com.wz.dhs.exception.BusinessException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import javax.validation.ValidationException;
import java.util.List;
import java.util.stream.Collectors;

public class ValidationUtils {

    // 对目标对象进行验证，并返回验证结果
    public static <T> ValidationResults validate(T target) throws ValidationException {
        DataBinder binder = new DataBinder(target);
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.afterPropertiesSet();
        binder.setValidator(validator);
        binder.validate();
        BindingResult result = binder.getBindingResult();
        if (result.hasErrors()) {
            List<String> errorMessages = result.getAllErrors()
                    .stream()
                    .map(objectError -> objectError.getDefaultMessage())
                    .collect(Collectors.toList());
            throw new BusinessException("70001",String.join(",", errorMessages));
        }
        return new ValidationResults(true, null);
    }

    // 定义验证结果数据结构
    public static class ValidationResults {

        private boolean valid;
        private String message;

        public ValidationResults(boolean valid, String message) {
            this.valid = valid;
            this.message = message;
        }

        public boolean isValid() {
            return valid;
        }

        public void setValid(boolean valid) {
            this.valid = valid;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }
}
